<template>
  <view class="page">
    <view class="ticket-box">
      <Sub-title :label="detail.title || '活动名称'" padding="0 0 20rpx 0" />
      <u-gap height="1rpx" bgColor="#D9D9D999" />
      <Sub-title label="选择场次（当地时间）" size="28rpx" :bold="false" color="#555" />
      <view
        v-for="(i, k) in dataList"
        :key="k"
        class="time-item"
        :class="{ checked: i.checked }"
        @click="chooseTime(i)"
      >
        <text>{{ i.day }}</text>
        <text>{{ i.week }}</text>
        <u-text
          :text="i.open_hours"
          size="28rpx"
          :bold="i.checked"
          align="center"
          line-height="40rpx"
          :color="i.checked ? '#3BA199' : '#979797'"
        />
      </view>
      <u-gap height="1rpx" margin-top="20" bg-color="#D9D9D999" />
      <view class="f-row">
        <u-text text="购买数量" color="#555555" size="28rpx" />
        <view class="number-box">
          <u-icon name="minus" color="#BABABA" size="28rpx" @click="changeMinus" />
          <text>{{ number }}</text>
          <u-icon name="plus" color="#BABABA" size="28rpx" @click="changePlus" />
        </view>
      </view>
    </view>
    <view class="ticket-box">
      <Sub-title label="优惠信息" padding="0 0 20rpx 0" />
      <view class="f-row">
        <u-text text="平台优惠券" color="#3BA199" size="28rpx" />
        <view style="flex: 2" @click="handleCoupon">
          <u-input
            v-model="coupon.name"
            disabled
            disabled-color="#ffffff"
            :placeholder="couponList.length > 0 ? '请选择优惠券' : '暂无优惠券'"
            font-size="28rpx"
            suffix-icon="arrow-right"
            suffix-icon-style="color: #909399"
            :placeholder-style="placeholderStyle"
            border="none"
          />
        </view>
      </view>
    </view>
    <view class="f-row mb">
      <u-icon :name="isAgree ? checked : unCheck" @click="isAgree = !isAgree" />
      <view class="f-label">
        点击“提交订单”则表示您已详细阅读同意并接受
        <text @click="handleProtocol"> 《丘山阅平台服务协议》 </text>
      </view>
    </view>
    <view class="btn">
      <view class="left">
        <view style="margin-right: 10rpx;">总价</view>
        <view v-if="isPlus">
          <u-text
            color="#909090"
            decoration="line-through"
            size="24rpx"
            :text="`原价：${countPrice}`"
          />
          <u-text color="#FF3E3E" :text="`会员价：${newPrice}`" size="24rpx" />
        </view>
        <u-text v-else color="#ff3e3e" mode="price" :text="countPrice" size="32rpx" />
      </view>
      <view class="right">
        <view
          class="right-btn"
          :class="{ disabled: !checkTime || !isAgree }"
          @click="checkout"
        >
          提交订单
        </view>
      </view>
    </view>
    <Coupon-popup
      v-model="couponShow"
      :list="couponList"
      @close="closeCoupon"
      @confirm="confirmCoupon"
    />
  </view>
</template>

<script>
import CouponPopup from "@/pages/home/cp/CouponPopup";

import { homeOrderTicket, homeAddOrder } from "@/request/homeApi.js";
import { myCouponList } from "@/request/myApi.js";
export default {
  components: { CouponPopup },
  data() {
    return {
      checked: require("@/static/mall/checked2.png"),
      unCheck: require("@/static/mall/check.png"),
      goodsId: "", // 活动ID
      goodsType: "", // 活动类型 information动态信息，party吃喝玩乐，subject主题活动，project娱乐项目
      isAgree: false, // 同意协议
      page: 1, // 页数
      number: 1, // 购票数量
      detail: {}, // 场地信息
      dataList: [], // 场次列表
      coupon: {}, // 优惠券信息
      couponShow: false, // 优惠券弹窗
      couponList: [], // 优惠券列表
      countPrice: "0.00", // 总金额
    };
  },
  onLoad(e) {
    this.goodsId = e.id;
    this.goodsType = e.type;
    this.getData();
  },
  computed: {
    // 是否已选时段
    checkTime() {
      return this.dataList.some((i) => i.checked);
    },

    isPlus() {
      let user = this.$getStorage("USER_INFO");
      return user.isPlus;
    },
    newPrice() {
      let user = this.$getStorage("USER_INFO");
      return parseFloat(this.countPrice * (parseFloat(user.memberRebate) / 10)).toFixed(
        2
      );
    },
  },
  methods: {
    // 获取活动场次
    getData() {
      let data = {
        type: this.goodsType,
        id: this.goodsId,
        page: this.page,
        pageSize: 10,
      };
      homeOrderTicket(data).then((res) => {
        if (res.code == 1) {
          this.detail = res.data.info;
          let list = res.data.list;
          list.forEach((i) => {
            i.checked = false;
          });
          this.dataList = list;
        } else {
          setTimeout(() => {
            uni.navigateBack({ delta: 1 });
          }, 1500);
        }
      });
    },
    // 选择时段
    chooseTime(val) {
      this.dataList.forEach((i) => {
        if (i.key == val.key) {
          i.checked = !i.checked;
        } else {
          i.checked = false;
        }
      });
      this.coupon = { name: "" };
      this.setCountPrice();
      this.getCouponList();
    },
    // 设置总金额
    setCountPrice() {
      if (this.dataList.some((i) => i.checked)) {
        let row = this.dataList.find((i) => i.checked);
        let oprice = this.number * parseFloat(row?.member_price || 0);
        if (this.coupon?.type == "reduction") {
          this.countPrice = (oprice - parseFloat(this.coupon.price)).toFixed(2);
        } else if (this.coupon?.type == "discount") {
          let zk = this.coupon.discount;
          let discount = zk > 10 ? this.$bcdiv(zk, 100) : this.$bcdiv(zk, 10);
          this.countPrice = (oprice * discount).toFixed(2);
        } else {
          this.countPrice = oprice.toFixed(2);
        }
      }
    },
    // 获取优惠券列表
    getCouponList() {
      let data = {
        shop_id: 0, // 不需要指定店铺
        page: 1,
        state: 1,
        price: this.countPrice,
      };
      this.couponList = [];
      myCouponList(data).then((res) => {
        if (res.code == 1) {
          this.couponList = res.data.data;
        }
      });
    },
    // 打开优惠券弹窗
    handleCoupon() {
      this.couponShow = true;
    },
    // 关闭优惠券弹窗
    closeCoupon() {
      this.couponShow = false;
    },
    // 选择优惠券
    confirmCoupon(v) {
      if (v.type == "reduction") {
        v.name = `满${Number(v.limit)}减${Number(v.price)}`;
      }
      if (v.type == "discount") {
        v.name = `满${Number(v.limit)}打${Number(v.discount)}折`;
      }
      if (v.choice) {
        this.coupon = v;
      } else {
        this.coupon = { name: "" };
      }
      this.setCountPrice();
      this.couponShow = false;
    },
    // 数组去重并字符串
    unique(arr) {
      return Array.from(new Set(arr)).join(",");
    },
    // 跳转协议
    handleProtocol() {
      uni.navigateTo({ url: "/pages/parse/index?type=order" });
    },
    // 减少数量
    changeMinus() {
      if (this.number <= 1) return;
      this.number--;
      this.setCountPrice();
    },
    // 增加数量
    changePlus() {
      if (this.number >= 99) return;
      this.number++;
      this.setCountPrice();
    },
    // 提交订单
    checkout() {
      if (!this.checkTime || !this.isAgree) return;
      let day = this.dataList.find((i) => i.checked);
      let data = {
        type: this.goodsType,
        id: this.goodsId,
        one_day: day.day,
        coupon_id: this.coupon?.id,
        number: this.number,
      };
      homeAddOrder(data).then((res) => {
        if (res.code == 1) {
          let { list, token } = res.data;
          if (list[0].pay_state == 1) {
            uni.redirectTo({
              url: `/pages/mall/payed?id=${list[0].order_id}&type=activity`,
            });
          } else {
            uni.navigateTo({
              url: `/pages/mall/cashier?token=${token}&data=${JSON.stringify(list)}`,
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 20rpx;
  min-height: calc(100vh - 200rpx);
  background-color: #f5f5f5;
  .ticket-box {
    background: #ffffff;
    box-shadow: 0 0 20rpx rgba(186, 186, 186, 0.2);
    padding: 30rpx;
    border-radius: 10px;
    margin-bottom: 30rpx;
    position: relative;
    .time-item {
      display: inline-block;
      padding: 18rpx 28rpx;
      width: calc(50% - 70rpx);
      background-color: #ffffff;
      border: 1rpx solid #bababa;
      border-radius: 10rpx;
      color: #979797;
      text-align: center;
      font-size: 28rpx;
      margin-right: 20rpx;
      margin-bottom: 20rpx;
      line-height: 40rpx;
      &:nth-child(2n + 1) {
        margin-right: 0;
      }
    }
    .checked {
      font-weight: 600;
      color: $active-color;
      border: 1rpx solid transparent;
      background-color: #cee7e5;
    }
  }
  .f-row {
    display: flex;
    justify-content: start;
    align-items: center;
    padding: 40rpx 0 10rpx 0;
    .number-box {
      width: auto;
      min-width: 100rpx;
      height: 44rpx;
      line-height: 44rpx;
      padding: 0 14rpx;
      background-color: #f5f5f5;
      border-radius: 44rpx;
      font-size: 24rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .f-label {
      flex: 1;
      margin-left: 20rpx;
      color: #979797;
      font-size: 24rpx;
      text {
        color: #1a98fc;
      }
    }
  }
  .mb {
    margin-bottom: 200rpx;
  }
  .btn {
    position: fixed;
    background-color: #fff;
    box-shadow: 0 0 8rpx rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    height: 126rpx;
    padding: 20rpx;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 9;
    .left {
      flex: 1;
      margin-left: 50rpx;
      color: #222222;
      font-size: 24rpx;
      display: flex;
      align-items: center;
    }
    .right {
      flex: 1;
      .right-btn {
        width: 308rpx;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 28rpx;
        text-align: center;
        color: $active-color;
        background-color: #cee7e5;
        border-radius: 40rpx;
        transition: all 0.5s;
      }
      .disabled {
        color: #cacaca;
        background-color: #f8f8f8;
      }
    }
  }
}
</style>
